package com.kevin.netty.starter;

import com.kevin.netty.starter.annotation.NettyHandler;
import com.kevin.netty.starter.preperties.NettyProperties;
import com.kevin.netty.starter.preperties.ServerProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.context.ConfigurableWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class AnnotationListener implements ApplicationListener<ApplicationStartedEvent> {

    private final NettyProperties nettyProperties;

    public void onApplicationEvent(ApplicationStartedEvent event) {
        if (event.getApplicationContext() instanceof ConfigurableWebServerApplicationContext) {
            Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(NettyHandler.class);
            ConfigurableListableBeanFactory conf = event.getApplicationContext().getBeanFactory();
            List<Object> beansWithNettyHandlerAnnotation = new ArrayList<>();

            for (String beanName : beans.keySet()) {
                beansWithNettyHandlerAnnotation.add(conf.getSingleton(beanName));
            }

            if (!CollectionUtils.isEmpty(beansWithNettyHandlerAnnotation)) {
                for (ServerProperties properties : this.nettyProperties.getServers()) {
                    new NettyServer(properties, beansWithNettyHandlerAnnotation);
                }
            }
        }
    }

}
